<template>
    <div class="installed-apps">
        <el-card class="apps-card">
            <div class="card-header">
                <h3>已安装的应用({{ filteredApps.length }})</h3>
                <div class="header-actions">
                    <el-input v-model="searchKeyword" placeholder="搜索应用" clearable
                        style="width: 300px; margin-right: 15px" @clear="handleSearch" @keyup.enter="handleSearch">
                        <template #prefix>
                            <el-icon>
                                <Search />
                            </el-icon>
                        </template>
                    </el-input>
                    <el-button-group style="margin-right: 15px">
                        <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="changeViewMode('list')"
                            title="列表视图">
                            <el-icon>
                                <List />
                            </el-icon>
                        </el-button>
                        <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="changeViewMode('grid')"
                            title="网格视图">
                            <el-icon>
                                <Grid />
                            </el-icon>
                        </el-button>
                        <el-button :type="viewMode === 'tile' ? 'primary' : ''" @click="changeViewMode('tile')"
                            title="磁贴视图">
                            <el-icon>
                                <Menu />
                            </el-icon>
                        </el-button>
                    </el-button-group>
                    <el-button :icon="Refresh" @click="refreshApps">刷新</el-button>
                </div>
            </div>

            <!-- 列表视图 -->
            <div v-if="viewMode === 'list'" class="apps-container"
                :style="{ height: windowStore.winHeight - 200 - (windowStore.isMaximized ? 20 : 0) + 'px' }">
                <el-table :data="filteredApps" style="width: 100%" v-loading="loading"
                    element-loading-text="正在加载已安装的应用..." stripe @sort-change="handleSortChange" height="100%">
                    <!-- 表格列保持不变 -->
                    <el-table-column prop="name" label="应用名称" min-width="200" sortable="custom">
                        <template #default="scope">
                            <div class="app-info">
                                <div class="app-icon">
                                    <el-avatar :size="32" :src="scope.row.icon || defaultAppIcon" />
                                </div>
                                <span class="app-name" :title="scope.row.exePath">{{ scope.row.name }}</span>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="version" label="版本" width="120" sortable="custom" />

                    <el-table-column prop="installDate" label="安装日期" width="150" sortable="custom">
                        <template #default="scope">
                            {{ formatDate(scope.row.installDate) }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="size" label="大小" width="120" sortable="custom">
                        <template #default="scope">
                            {{ formatSize(scope.row.size) }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="publisher" label="发布者" min-width="150" sortable="custom" />

                    <el-table-column label="操作" width="180" fixed="right">
                        <template #default="scope">
                            <el-button type="danger" size="small" @click="uninstallApp(scope.row)"
                                style="margin-left: 5px">
                                卸载
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 罽格视图 -->
            <div v-else-if="viewMode === 'grid'" class="grid-view-container"
                :style="{ height: windowStore.winHeight - 180 - (windowStore.isMaximized ? 20 : 0) + 'px' }">
                <el-row :gutter="20">
                    <el-col v-for="app in filteredApps" :key="app.id" :xs="24" :sm="12" :md="8" :lg="6" :xl="4"
                        style="margin-bottom: 20px">
                        <el-card class="app-grid-card" shadow="hover">
                            <div class="app-grid-content">
                                <div class="app-grid-icon">
                                    <el-avatar :size="48" :src="app.icon || defaultAppIcon" />
                                </div>
                                <div class="app-grid-info">
                                    <h4 class="app-grid-name" :title="app.name">{{ app.name }}</h4>
                                    <p class="app-grid-version">版本: {{ app.version || '未知' }}</p>
                                    <p class="app-grid-size">大小: {{ formatSize(app.size) }}</p>
                                </div>
                                <div class="app-grid-actions">
                                    <el-button type="danger" size="small" @click="uninstallApp(app)">
                                        卸载
                                    </el-button>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- 磁贴视图 -->
            <div v-else-if="viewMode === 'tile'" class="tile-view-container"
                :style="{ height: windowStore.winHeight - 180 - (windowStore.isMaximized ? 20 : 0) + 'px' }">
                <el-row :gutter="15">
                    <el-col v-for="app in filteredApps" :key="app.id" :xs="24" :sm="12" :md="8" :lg="6" :xl="3"
                        style="margin-bottom: 15px">
                        <el-card class="app-tile-card" shadow="hover">
                            <div class="app-tile-content">
                                <div class="app-tile-icon">
                                    <el-avatar :size="32" :src="app.icon || defaultAppIcon" />
                                </div>
                                <div class="app-tile-info">
                                    <h4 class="app-tile-name" :title="app.name">{{ app.name }}
                                    </h4>
                                    <p class="app-tile-version">{{ app.version || '未知' }}</p>
                                </div>
                                <div class="app-tile-dropdown">
                                    <el-dropdown @command="handleTileCommand($event, app)">
                                        <el-button type="primary" size="small" circle>
                                            <el-icon>
                                                <MoreFilled />
                                            </el-icon>
                                        </el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="uninstall" divided>
                                                    <el-icon>
                                                        <Delete />
                                                    </el-icon>
                                                    卸载
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </el-card>
    </div>
</template>

<script>
    import { ref, computed, onMounted } from 'vue'
    import { Search, Refresh, List, Grid, Menu, MoreFilled, Promotion, Delete } from '@element-plus/icons-vue'
    import { useWindowStore } from '/src/stores/windowStore'
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { ipcRenderer } from 'electron'
    import fs from 'fs'

    export default {
        name: 'InstalledApps',
        components: {
            Search,
            Refresh,
            List,
            Grid,
            Menu,
            MoreFilled,
            Promotion,
            Delete
        },
        setup() {
            const windowStore = useWindowStore()
            const loading = ref(false)
            const apps = ref([])
            const searchKeyword = ref('')
            const sortProp = ref('')
            const sortOrder = ref('')
            const viewMode = ref('list') // 默认列表视图
            const renderStartTime = ref(0) // 添加这行 - 定义渲染开始时间

            // 默认应用图标
            const defaultAppIcon = ''
            const MAX_RENDER_ITEMS = 1000; // 限制最大渲染数量
            // 过滤和排序后的应用列表
            const filteredApps = computed(() => {
                let result = [...apps.value]

                // 搜索过滤
                if (searchKeyword.value) {
                    const keyword = searchKeyword.value.toLowerCase()
                    result = result.filter(app =>
                        app.name.toLowerCase().includes(keyword) ||
                        (app.publisher && app.publisher.toLowerCase().includes(keyword)) ||
                        (app.version && app.version.toLowerCase().includes(keyword))
                    )
                }

                // 限制渲染数量，防止性能问题
                if (result.length > MAX_RENDER_ITEMS) {
                    console.warn(`应用数量超过限制 (${result.length} > ${MAX_RENDER_ITEMS})，已截取前 ${MAX_RENDER_ITEMS} 个`)
                    result = result.slice(0, MAX_RENDER_ITEMS)
                }

                // 排序
                if (sortProp.value) {
                    result.sort((a, b) => {
                        let aVal = a[sortProp.value]
                        let bVal = b[sortProp.value]

                        // 特殊处理大小排序 - 使用原始大小值
                        if (sortProp.value === 'size') {
                            aVal = a.rawSize || 0
                            bVal = b.rawSize || 0
                        }

                        // 处理空值
                        if (aVal === undefined || aVal === null) aVal = ''
                        if (bVal === undefined || bVal === null) bVal = ''

                        // 大小排序使用数值比较
                        if (sortProp.value === 'size') {
                            if (sortOrder.value === 'ascending') {
                                return aVal - bVal
                            } else {
                                return bVal - aVal
                            }
                        }

                        // 其他字段使用字符串比较
                        // 转换为字符串进行比较
                        if (typeof aVal !== 'string') aVal = aVal.toString()
                        if (typeof bVal !== 'string') bVal = bVal.toString()

                        // 忽略大小写比较
                        aVal = aVal.toLowerCase()
                        bVal = bVal.toLowerCase()

                        if (sortOrder.value === 'ascending') {
                            return aVal.localeCompare(bVal)
                        } else {
                            return bVal.localeCompare(aVal)
                        }
                    })
                }

                return result
            })

            // 切换视图模式
            const changeViewMode = (mode) => {
                viewMode.value = mode
            }

            // 在 loadInstalledApps 函数中添加数据验证和去重
            const loadInstalledApps = async () => {
                renderStartTime.value = Date.now()
                loading.value = true
                try {
                    const result = await ipcRenderer.invoke('system-info', 'installed')
                    console.log('已安装应用列表:', result)
                    if (result && result.code === 200) {
                        console.log('已安装应用列表:', result.data)
                        // 数据去重
                        const uniqueApps = []
                        const appKeys = new Set()

                        for (const app of result.data) {
                            // 创建唯一键
                            const appKey = `${app.name}-${app.version || ''}`

                            // 避免重复
                            if (!appKeys.has(appKey)) {
                                appKeys.add(appKey)

                                const appWithIcon = {
                                    ...app,
                                    id: appKey,
                                    size: getAppSize(app), // 格式化后的大小，用于显示
                                    rawSize: app.size, // 原始大小值，用于排序
                                    installDate: getAppInstallDate(app),
                                    publisher: app.publisher || '未知'
                                }

                                // 验证数据完整性
                                if (appWithIcon.name && appWithIcon.name.trim() !== '') {
                                    // 异步获取图标
                                    appWithIcon.icon = await getAppIcon(app)
                                    uniqueApps.push(appWithIcon)
                                }
                            }
                        }

                        apps.value = uniqueApps
                        ElMessage.success(`成功加载 ${apps.value.length} 个已安装应用`)
                    } else {
                        ElMessage.error('加载应用列表失败')
                    }
                } catch (error) {
                    ElMessage.error('加载应用列表时发生错误: ' + error.message)
                    console.error(error)
                } finally {
                    loading.value = false
                    const renderTime = Date.now() - renderStartTime.value
                    console.log(`应用列表渲染耗时: ${renderTime}ms`)

                    if (renderTime > 5000) {
                        ElMessage.warning('应用列表较大，渲染耗时较长')
                    }
                }
            }

            // 获取应用图标
            const getAppIcon = async (app) => {
                // 如果应用数据中已经有图标，直接返回
                if (app.icon) {
                    return app.icon;
                }

                // 根据优先级选择 .exe 文件路径
                let exePath = null;

                // 按优先级顺序检查路径
                const pathsToCheck = [app.exePath, app.uninstallString, app.path];

                for (let path of pathsToCheck) {
                    if (path && typeof path === 'string') {
                        // 清理路径
                        path = path.trim();

                        // 移除引号
                        if (path.startsWith('"') && path.endsWith('"')) {
                            path = path.substring(1, path.length - 1);
                        }

                        // 检查是否为 .exe 文件或从中提取 .exe 路径
                        if (path.toLowerCase().endsWith('.exe')) {
                            exePath = path;
                            break;
                        } else {
                            // 尝试从命令行参数中提取 exe 路径
                            const match = path.match(/^(.+?\.exe)/i);
                            if (match) {
                                exePath = match[1];
                                break;
                            }
                        }
                    }
                }
                // 尝试从应用路径获取图标
                try {
                    // 通过 IPC 获取应用图标
                    const result = await ipcRenderer.invoke('get-icon', app.name, exePath);
                    console.log('get-icon result:' + app.name, result);
                    if (result.code == 200) {
                        // const iconData = await ipcRenderer.invoke('get-app-icon', { name: app.name, path: exePath });
                        // if (iconData) {
                        return `data:image/png;base64,${result.data.iconBase64}`;
                    }
                } catch (e) {
                    console.log('获取应用图标失败:', e);
                }

                // 返回默认图标
                return defaultAppIcon;
            }

            // 获取应用大小
            const getAppSize = (app) => {
                // 如果应用数据中包含大小信息则返回，否则返回默认值
                if (app.size) {
                    return app.size
                }
                // 可以通过其他方式获取应用大小
                return '未知'
            }

            // 获取应用安装日期
            const getAppInstallDate = (app) => {
                // 如果应用数据中包含安装日期则返回，否则返回默认值
                if (app.installDate) {
                    return app.installDate
                }
                // 可以通过其他方式获取安装日期
                return new Date().toISOString()
            }

            // 格式化日期
            const formatDate = (dateString) => {
                if (!dateString) return '未知'
                try {
                    const date = new Date(dateString)
                    return date.toLocaleDateString('zh-CN')
                } catch {
                    return '未知'
                }
            }

            // 格式化大小
            const formatSize = (size) => {
                if (!size) return '未知'

                // 如果是已经格式化的字符串，直接返回
                if (typeof size === 'string') {
                    // 检查是否已经是格式化的大小
                    if (size.includes('B') || size.includes('KB') || size.includes('MB') || size.includes('GB')) {
                        return size
                    }
                    return size
                }

                // 如果是数字，转换为可读格式
                if (typeof size === 'number') {
                    if (size < 1024) return size + ' B'
                    if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
                    if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + ' MB'
                    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
                }

                return '未知'
            }

            // 处理排序变化
            const handleSortChange = ({ prop, order }) => {
                sortProp.value = prop
                sortOrder.value = order
            }

            // 处理搜索
            const handleSearch = () => {
                // 搜索逻辑已在 computed 中实现
            }

            // 刷新应用列表
            const refreshApps = () => {
                loadInstalledApps()
            }

            // 卸载应用（需要管理员权限）
            const uninstallApp = async (app) => {
                try {
                    await ElMessageBox.confirm(
                        `确定要卸载 "${app.name}" 吗？此操作不可撤销。`,
                        '确认卸载',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    )

                    // 这里需要实现卸载逻辑
                    // 可能需要调用系统卸载程序或使用 Windows 的卸载命令
                    ElMessage.info('卸载功能正在开发中...')
                } catch {
                    // 用户取消操作
                }
            }

            onMounted(() => {
                loadInstalledApps()
            })

            return {
                windowStore,
                loading,
                apps,
                searchKeyword,
                filteredApps,
                defaultAppIcon,
                viewMode,
                handleSortChange,
                handleSearch,
                refreshApps,
                uninstallApp,
                formatDate,
                formatSize,
                changeViewMode,
                Search,
                Refresh,
                List,
                Grid,
                Menu
            }
        }
    }
</script>

<style scoped>
    .installed-apps {
        padding: 15px;
        height: 100%;
        box-sizing: border-box;
    }

    .apps-card {
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
    }

    .card-header h3 {
        margin: 0;
        font-size: 18px;
    }

    .apps-container,
    .grid-view-container,
    .tile-view-container {
        flex: 1;
        overflow-y: auto;
    }

    .app-info {
        display: flex;
        align-items: center;
    }

    .app-icon {
        margin-right: 10px;
    }

    .app-name {
        font-weight: 500;
    }

    :deep(.el-table) {
        flex: 1;
    }

    :deep(.el-table__row) {
        cursor: pointer;
    }

    :deep(.el-table__row:hover) {
        background-color: #f5f7fa;
    }

    /* 网格视图样式 */
    .app-grid-card {
        height: 100%;
    }

    .app-grid-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;
    }

    .app-grid-icon {
        margin-bottom: 15px;
    }

    .app-grid-info {
        flex: 1;
        margin-bottom: 15px;
    }

    .app-grid-name {
        margin: 0 0 10px 0;
        font-size: 16px;
        width: 250px;
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .app-grid-version,
    .app-grid-size {
        margin: 5px 0;
        font-size: 14px;
        color: #666;
    }

    .app-grid-actions {
        width: 100%;
    }

    /* 更新磁贴视图样式 */
    .app-tile-card {
        cursor: pointer;
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .app-tile-card:hover {
        border-color: #409eff;
    }

    .app-tile-content {
        display: flex;
        align-items: center;
        flex: 1;
    }

    .app-tile-icon {
        margin-right: 10px;
    }

    .app-tile-info {
        flex: 1;
        overflow: hidden;
        cursor: pointer;
    }

    .app-tile-name {
        margin: 0 0 5px 0;
        font-size: 14px;
        font-weight: 500;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .app-tile-version {
        margin: 0;
        font-size: 12px;
        color: #999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .app-tile-actions {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        gap: 5px;
    }

    .app-tile-actions .el-button {
        flex: 1;
        min-width: 0;
    }

    /* 滚动条样式 */
    .apps-container::-webkit-scrollbar,
    .grid-view-container::-webkit-scrollbar,
    .tile-view-container::-webkit-scrollbar {
        width: 6px;
    }

    .apps-container::-webkit-scrollbar-track,
    .grid-view-container::-webkit-scrollbar-track,
    .tile-view-container::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }

    .apps-container::-webkit-scrollbar-thumb,
    .grid-view-container::-webkit-scrollbar-thumb,
    .tile-view-container::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 10px;
    }

    .apps-container::-webkit-scrollbar-thumb:hover,
    .grid-view-container::-webkit-scrollbar-thumb:hover,
    .tile-view-container::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }
</style>